package com.demo.task.vm

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.orhanobut.logger.Logger
import dagger.hilt.android.scopes.ViewModelScoped
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject

@ViewModelScoped
class PlayerViewModel @Inject constructor() : ViewModel() {
    private val ids by lazy(LazyThreadSafetyMode.NONE) { mutableSetOf<String>() }
    private val flag = ConcurrentHashMap.newKeySet<String>()

    private val _playback = MutableSharedFlow<Unit>()
    val playback: SharedFlow<Unit> = _playback

    private var checkJob: Job? = null

    fun clearIds() {
        ids.clear()
        flag.clear()
    }

    fun setAwaitId(id: String) {
        ids.add(id)
        flag.add(id)
    }

    fun notifyCount(id: String) {
        flag.remove(id)
        val isEmpty = flag.isEmpty()
        Log.i(TAG, "notifyCount: $id flag$flag ids$ids $isEmpty")
        Logger.i("notifyCount: $id flag$flag ids$ids $isEmpty")
        if (isEmpty) {
            checkJob?.cancel()
            flag.addAll(ids)
            viewModelScope.launch {
                _playback.emit(Unit)
            }
        } else {
            check()
        }
    }

    private fun check() {
        checkJob?.cancel()
        checkJob = viewModelScope.launch {
            delay(2_000)
            Log.i(TAG, "check: ")
            if (flag.isNotEmpty()) {
                for (id in flag) {
                    notifyCount(id)
                }
            }
        }
    }

    companion object {
        private const val TAG = "PlayerViewModel"
    }
}